﻿using MainWebService;
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Web;

namespace MainWebService
{
    public class ServiceOperations
    {

        internal DataSet GetServices(int clientId, string hashCode)
        {
            //Dictionary<int, string> _dcData = new Dictionary<int, string>();
            List<int> lstDBIds = new List<int>();
            DataSet ds = new DataSet();
            DAO d = new DAO();
            List<SqlParameter> param = new List<SqlParameter>();
            param.Add(d.AddParameter("@ClientId", clientId));
            param.Add(d.AddParameter("@HashCode", hashCode));
            ds = d.ExecuteDataSet("P_GetServiceList", param);
            //if (ds.Tables.Count > 0 && ds.Tables[0].Rows.Count > 0)
            //{
            //    for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
            //    {
            //        _dcData.Add(Convert.ToInt32(ds.Tables[0].Rows[i]["ServiceId"]), Convert.ToString(ds.Tables[0].Rows[i]["ServiceName"]));
            //    }

            //}
            return ds;
        }

        internal List<ServiceType> GetServiceType()
        {
            List<ServiceType> _lstSType = new List<ServiceType>();
            ServiceType _sType = null;
            DAO d = new DAO();
            DataSet ds = new DataSet();
            ds = d.ExecuteDataSet("SELECT ServiceTypeId,ServiceTypeName,ServiceDescription,ServiceUrl FROM ServiceType ORDER BY ServiceTypeId ASC");
            if (Utility.IsValidDataSet(ds))
            {
                for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
                {
                    _sType = new ServiceType();
                    _sType.ServiceTypeId = Utility.GetInt(ds.Tables[0].Rows[i][0]);
                    _sType.ServiceName = Utility.GetString(ds.Tables[0].Rows[i][1]);
                    _sType.ServiceDescription = Utility.GetString(ds.Tables[0].Rows[i][2]);
                    _sType.ServiceUrl = Utility.GetString(ds.Tables[0].Rows[i][3]);
                    _lstSType.Add(_sType);
                }
            }
            return _lstSType;
        }

        internal string CreateService(string serviceName, string serviceType, string serviceSubType, int userId, string hashCode, string serviceDes, string serviceDetail, string iconURL, string serviceURL, ref int newServiceId)
        {
            object messgae = null;
            object serviceId = null;
            try
            {
                int tempId = 0;
                DAO d = new DAO();
                List<SqlParameter> param = new List<SqlParameter>();
                param.Add(d.AddParameter("@ServiceName", serviceName));
                param.Add(d.AddParameter("@ServiceDesc", serviceDes));
                param.Add(d.AddParameter("@ServiceDetail", serviceDetail));
                param.Add(d.AddParameter("@ServiceType", serviceType));
                param.Add(d.AddParameter("@ServiceSubType", serviceSubType));
                param.Add(d.AddParameter("@CreatedBy", userId));
                param.Add(d.AddParameter("@HashCode", hashCode));
                param.Add(d.AddParameter("@ImageURL", iconURL));
                param.Add(d.AddParameter("@ServiceURL", serviceURL));
                param.Add(d.AddParameter("@ServiceId", serviceId, SqlDbType.Int, 10, ParameterDirection.InputOutput));
                param.Add(d.AddParameter("@Messages", messgae, SqlDbType.VarChar, 500, ParameterDirection.InputOutput));
                d.ExecuteQuery("P_AddService", param, ref serviceId, ref messgae);
                if (serviceId != null && Int32.TryParse(serviceId.ToString(), out tempId))
                {
                    newServiceId = tempId;

                }

            }
            catch (Exception ex)
            {
                messgae = ex.Message.ToString();
            }
            return messgae.ToString();
        }

        internal List<ServiceDetails> GetServiceDetails(int clientId, string hashCode)
        {
            int serviceId = 0;
            List<ServiceDetails> lstService = null;
            ServiceDetails srvDetails = null;
            DataSet ds = new DataSet();
            DataTable dtUser = null;
            DataRow dr = null;
            DAO d = new DAO();
            int itemId = 0;
            List<SqlParameter> param = new List<SqlParameter>();
            param.Add(d.AddParameter("@ClientId", clientId));
            param.Add(d.AddParameter("@HashCode", hashCode));
            ds = d.ExecuteDataSet("P_GetServiceDetail", param);
            if (Utility.IsValidDataSet(ds))
            {
                if (Utility.IsValidDataSet(ds, 0))
                {
                    lstService = new List<ServiceDetails>();
                    for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
                    {
                        serviceId = Convert.ToInt32(ds.Tables[0].Rows[i]["ServiceId"]);
                        srvDetails = new ServiceDetails();
                        srvDetails.ServiceName = Convert.ToString(ds.Tables[0].Rows[i]["ServiceName"]);
                        srvDetails.ServiceId = Convert.ToInt32(ds.Tables[0].Rows[i]["ServiceId"]);
                        srvDetails.ServiceDetail = Convert.ToString(ds.Tables[0].Rows[i]["ServiceDetail"]);
                        srvDetails.ServiceType = Convert.ToString(ds.Tables[0].Rows[i]["ServiceType"]);
                        srvDetails.ServiceSubType = Convert.ToString(ds.Tables[0].Rows[i]["ServiceSubType"]);
                        srvDetails.ServiceDescription = Convert.ToString(ds.Tables[0].Rows[i]["ServiceDescription"]);
                        srvDetails.CreateDate = Convert.ToString(ds.Tables[0].Rows[i]["CreateDate"]);
                        srvDetails.DBId = Utility.GetInt(ds.Tables[0].Rows[i]["DBId"]);
                        srvDetails.DBName = Utility.GetString(ds.Tables[0].Rows[i]["DBName"]);
                        srvDetails.UserNamesList = Utility.GetString(ds.Tables[0].Rows[i]["Users"]);
                        srvDetails.ServiceURL = Utility.GetString(ds.Tables[0].Rows[i]["ServiceURL"]);
                        srvDetails.ImageIconURL = Utility.GetString(ds.Tables[0].Rows[i]["ImageIconURL"]);
                        srvDetails.ServiceQuestions = new List<Questions>();
                        srvDetails.ServiceQuestions = GetServiceQuestions(srvDetails.ServiceId);
                        string[] itemIds = Utility.GetString(ds.Tables[0].Rows[i]["UserIds"]).Split(',');
                        string[] userNames = Utility.GetString(ds.Tables[0].Rows[i]["Users"]).Split(',');
                        //Dictionary<int, string> lstService = new Dictionary<int, string>();
                        dtUser = new DataTable();
                        dtUser.Columns.Add(new DataColumn("Id"));
                        dtUser.Columns.Add(new DataColumn("Name"));
                        for (int j = 0; j < itemIds.Length; j++)
                        {

                            if (Int32.TryParse(itemIds[j], out itemId) && itemId > 0)
                            {
                                dr = dtUser.NewRow();
                                dr[0] = itemId;
                                dr[1] = userNames[j] != null ? Convert.ToString(userNames[j]) : "";
                                dtUser.Rows.Add(dr);
                            }
                        }

                        srvDetails.GetUserList = new DataSet();
                        srvDetails.GetUserList.Tables.Add(dtUser);
                        try
                        {
                            srvDetails.AdvanceProperties = GetServiceProperties(serviceId, clientId);
                        }
                        catch (Exception ex)
                        { }
                        lstService.Add(srvDetails);
                    }
                }
            }
            else
            {
                lstService = null;
            }


            return lstService;
        }

        private List<Questions> GetServiceQuestions(int serviceId)
        {
            List<Questions> lstQ = new List<Questions>();
            DataSet ds = new DataSet();
            DAO d = new DAO();
            List<SqlParameter> param = new List<SqlParameter>();
            param.Add(d.AddParameter("@ServiceId", serviceId));
            ds = d.ExecuteDataSet("P_GetServiceQuestions", param);
            Questions _q = null;
            if (Utility.IsValidDataSet(ds, 0))
            {
                for (int j = 0; j < ds.Tables[0].Rows.Count; j++)
                {
                    _q = new Questions();

                    _q.QuestionText = Utility.GetString(ds.Tables[0].Rows[j]["QuestionText"]);
                    _q.QuestionType = Utility.GetString(ds.Tables[0].Rows[j]["QuestionType"]).Split('(')[0];
                    _q.QuestionId = Utility.GetInt(ds.Tables[0].Rows[j]["QuestionId"]);
                    _q.IsNumeric = Utility.GetBoolean(ds.Tables[0].Rows[j]["IsNumeric"]);
                    _q.IsAfterSubmittingScan = Utility.GetBoolean(ds.Tables[0].Rows[j]["IsAfterSubmittingScan"]);
                    _q.IsBeforSubmittingScan = Utility.GetBoolean(ds.Tables[0].Rows[j]["IsBeforSubmittingScan"]);
                    _q.IsSubmittingInValidScan = Utility.GetBoolean(ds.Tables[0].Rows[j]["IsSubmittingInValidScan"]);
                    _q.IsSubmittingValidScan = Utility.GetBoolean(ds.Tables[0].Rows[j]["IsSubmittingValidScan"]);
                    _q.AnswerOptions = Utility.GetString(ds.Tables[0].Rows[j]["QuestionOptions"]) != "" ? Utility.GetString(ds.Tables[0].Rows[j]["QuestionOptions"]).Split(',').ToList<string>() : null;
                    lstQ.Add(_q);
                }

            }
            return lstQ;
        }

        internal string CreateService(ValidateScan scan)
        {
            int databaseId = 0;
            if (scan.dbId <= 0 && scan.databaseName != null && scan.databaseName.Trim().Length > 0)
            {
                DatabaseDetails _details = new DatabaseDetails();
                _details.DBName = scan.databaseName.Trim();
                _details.IsCaseSensitiveValidation = false;
                _details.ScanDataList = null;
                _details.CreatedBy = scan.userId;
                _details.ServiceDetails = null;
                _details.CreateDatabase(ref databaseId);
            }
            else
            {
                databaseId = scan.dbId;
            }
            object messgae = null;
            object serviceId = null;
            try
            {
                int tempId = 0;
                DAO d = new DAO();
                List<SqlParameter> param = new List<SqlParameter>();
                param.Add(d.AddParameter("@ServiceName", scan.serviceName));
                param.Add(d.AddParameter("@ServiceDesc", scan.serviceDes));
                param.Add(d.AddParameter("@ServiceDetail", scan.serviceDetail));
                param.Add(d.AddParameter("@ServiceType", scan.serviceType));
                param.Add(d.AddParameter("@ServiceSubType", scan.serviceSubType));
                param.Add(d.AddParameter("@CreatedBy", scan.userId));
                param.Add(d.AddParameter("@HashCode", scan.hashCode));
                param.Add(d.AddParameter("@ImageURL", scan.iconURL));
                param.Add(d.AddParameter("@ServiceURL", scan.serviceURL));
                param.Add(d.AddParameter("@DatabaseId", databaseId));
                param.Add(d.AddParameter("@ServiceId", serviceId, SqlDbType.Int, 10, ParameterDirection.InputOutput));
                param.Add(d.AddParameter("@Messages", messgae, SqlDbType.VarChar, 500, ParameterDirection.InputOutput));
                d.ExecuteQuery("P_AddService", param, ref serviceId, ref messgae);
                if (serviceId != null && Int32.TryParse(serviceId.ToString(), out tempId))
                {
                    messgae = serviceId;
                }
            }
            catch (Exception ex)
            {
                messgae = ex.Message.ToString();
            }
            return messgae.ToString();
        }

        internal void UpdateService(int UserId, string HashCode, int ServiceId, string serviceName, string serviceDetail)
        {
            try
            {
                DAO d = new DAO();
                List<SqlParameter> param = new List<SqlParameter>();
                param.Add(d.AddParameter("@UserId", UserId));
                param.Add(d.AddParameter("@HashCode", HashCode));
                param.Add(d.AddParameter("@ServiceId", ServiceId));
                param.Add(d.AddParameter("@ServiceName", serviceName));
                param.Add(d.AddParameter("@ServiceDetail", serviceDetail));
                d.ExecuteQuery("P_UpdateService", param);
            }
            catch (Exception ex)
            {
            }
        }

        internal string DeleteService(int serviceId, string hashCode)
        {

            try
            {
                DAO d = new DAO();
                List<SqlParameter> param = new List<SqlParameter>();
                param.Add(d.AddParameter("@HashCode", hashCode));
                param.Add(d.AddParameter("@ServiceId", serviceId));
                int result = d.ExecuteQuery("P_DeleteService", param);
                return result > 0 ? "Deleted Successfully" : "Error while deleting service";
            }
            catch (Exception ex)
            {
                return "Error while deleting service";
            }
        }

        internal string AddServiceProperties(int serviceId, int clientId, ServiceProperties srvProperties)
        {
            try
            {
                DAO d = new DAO();
                List<SqlParameter> param = new List<SqlParameter>();
                param.Add(d.AddParameter("@ClientId", clientId));
                param.Add(d.AddParameter("@ServiceId", serviceId));
                if (srvProperties != null)
                {
                    param.Add(d.AddParameter("@AllowedBarCodes", srvProperties.AllowedBarCodes));
                    param.Add(d.AddParameter("@DeleteSavedScans", srvProperties.DeleteSavedScans));
                    param.Add(d.AddParameter("@EditSavedAnswers", srvProperties.EditSavedAnswers));
                    param.Add(d.AddParameter("@EmailMeOnUploadEmailId", srvProperties.EmailMeOnUploadEmailId));
                    param.Add(d.AddParameter("@ViewOtherScans", srvProperties.ViewOtherScans));

                }
                int result = d.ExecuteQuery("P_AddServiceProperties", param);
                return result > 0 ? "Added Successfully" : "Error while deleting service";
            }
            catch (Exception ex)
            {
                return "Error while deleting service";
            }
        }

        internal ServiceProperties GetServiceProperties(int serviceId, int clientId)
        {
            ServiceProperties prop = new ServiceProperties();
            DAO d = new DAO();
            DataSet ds = new DataSet();
            ds = d.ExecuteDataSet("SELECT PropertyValue FROM ServiceProperties Where ServiceId=" + serviceId.ToString() + " AND CreatedBy=" + clientId.ToString());
            if (Utility.IsValidDataSet(ds))
            {
                prop.DeleteSavedScans = Utility.GetBoolean(ds.Tables[0].Rows.Count > 0 ? ds.Tables[0].Rows[0][0] : "false");
                prop.EditSavedAnswers = Utility.GetBoolean(ds.Tables[0].Rows.Count > 0 ? ds.Tables[0].Rows[1][0] : "false");
                prop.ViewOtherScans = Utility.GetBoolean(ds.Tables[0].Rows.Count > 1 ? ds.Tables[0].Rows[2][0] : "false");
                prop.EmailMeOnUploadEmailId = Utility.GetString(ds.Tables[0].Rows.Count > 2 ? ds.Tables[0].Rows[3][0] : "");
                prop.AllowedBarCodes = Utility.GetString(ds.Tables[0].Rows.Count > 3 ? ds.Tables[0].Rows[4][0] : "");
            }
            return prop;
        }
    }
}